﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "ChangeCategoryCtrl" in code, svc and config file together.
public class ChangeCategoryCtrl : IChangeCategoryCtrl
{
    public void DoWork()
    {
    }

    public List<Category> GetAllCate()
    {
        List<Category> listCate = new List<Category>();
        DataClassesDataContext db = new DataClassesDataContext();
        List<Category_Table> cates = db.Category_Tables.ToList();
        foreach (Category_Table cte in cates)
        {
            Category c = new Category(cte);
            listCate.Add(c);
        }
        return listCate;
    }

    public void AddCate(Guid categoryID, String categoryName, Boolean categoryStatus, Guid categoryFather)
    {
        try
        {
            DataClassesDataContext db = new DataClassesDataContext();
            var data = from tab in db.Category_Tables
                       select tab;
            foreach (var item in data)
            {
                categoryID = Guid.NewGuid();
                item.CategoryID = categoryID;
                item.CategoryName = categoryName;
                item.CategoryStatus = categoryStatus;
                item.CategoryFather = categoryFather;
                db.SubmitChanges();
            }
        }
        catch (SqlException ex)
        {
            // Handle more specific SqlException exception here.
        }
        catch (Exception ex)
        {
            // Handle generic ones here.
        }
    }

    public void MergeCate(Guid categoryID1, Guid categoryID2)
    {
        //Disable Old Category
        DataClassesDataContext db = new DataClassesDataContext();
        var data1 = from tab in db.Category_Tables
                    where tab.CategoryID.Equals(categoryID2)
                    select tab;
        if (data1.ToList().Count == 1)
        {
            foreach (var item in data1)
            {
                item.CategoryStatus = false;
                db.SubmitChanges();
            }

            //Merge To new Category
            var data2 = from tab2 in db.Item_Tables
                        where tab2.Category_ID.Equals(categoryID2)
                        select tab2;
            if (data2.ToList().Count == 1)
            {
                foreach (var item in data2)
                {
                    item.Category_ID = categoryID1;
                    db.SubmitChanges();
                }
            }
        }
    }
}
